package com.kgc.kmall.interceptors;

import com.alibaba.fastjson.JSON;
import com.kgc.kmall.annotations.LoginRequired;
import com.kgc.kmall.util.CookieUtil;
import com.kgc.kmall.util.HttpclientUtil;
import com.kgc.kmall.util.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    //创建拦截器
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //确保请求是访问控制器的请求
        if(handler.getClass().equals(org.springframework.web.method.HandlerMethod.class)){
            //获取方法的注解信息
            HandlerMethod hm=(HandlerMethod) handler;
            LoginRequired methodAnnotation = hm.getMethodAnnotation(LoginRequired.class);
            if(methodAnnotation==null){
              //没有必须拦截,没有添加注解
                System.out.println("拦截器直接执行");
                return true;
            }else{
                String token="";
                String oldToken = CookieUtil.getCookieValue(request, "oldToken", true);
                if(StringUtils.isNotBlank(oldToken)){
                    token=oldToken;
                }
                String newToken = request.getParameter("token");
                if (StringUtils.isNotBlank(newToken)) {
                    token = newToken;
                }
                //token为空验证不通过
                String result="fail";
                Map<String,String> successMap = new HashMap<>();
                if (StringUtils.isNotBlank(token)){
                    String ip = request.getRemoteAddr();
                    if(StringUtils.isBlank(ip)||ip.equals("0:0:0:0:0:0:0:1")){
                        ip = "127.0.0.1";
                    }
                    //验证中心
                    String successJson  = HttpclientUtil.doGet("http://localhost:8086/verify?token=" + token+"&currentIp="+ip);
                    successMap = JSON.parseObject(successJson,Map.class);
                    result = successMap.get("status");
                }
                //判断value是true还是false
               boolean loginSuccess=methodAnnotation.value();
               if(loginSuccess){
                   System.out.println("必须登录");
                   if(!result.equals("success")){
                       //重定向会passport登录
                       StringBuffer requestURL = request.getRequestURL();
                       response.sendRedirect("http://localhost:8086/index?ReturnUrl="+requestURL);
                       return false;
                   }
                   // 需要将token携带的用户信息写入
                   request.setAttribute("memberId", successMap.get("memberId"));
                   request.setAttribute("nickname", successMap.get("nickname"));
                   //验证通过，覆盖cookie中的token
                   if(StringUtils.isNotBlank(token)){
                       CookieUtil.setCookie(request,response,"oldToken",token,60*60*2,true);
                   }
               }else{
                   System.out.println("没有登录,也可以放行");
                   if(result.equals("success")){
                       request.setAttribute("memberId", successMap.get("memberId"));
                       request.setAttribute("nickname", successMap.get("nickname"));
                       //验证通过，覆盖cookie中的token
                       if(StringUtils.isNotBlank(token)){
                           CookieUtil.setCookie(request,response,"oldToken",token,60*60*2,true);
                       }
                   }
               }
            }
        }
        return true;
    }
}